package com.adityayadav.mini.server;

public class HTTPRequestParser {

	private byte[] buffer = new byte[0];
	private byte[] separator = new byte[]{13,10};
	
	
	public void addToBuffer(byte[] part){
		int length = buffer.length + part.length;
		byte[] buffer2 = new byte[length];
		System.arraycopy(buffer, 0, buffer2, 0, buffer.length);
		System.arraycopy(part, 0, buffer2, buffer.length, part.length);
		buffer = buffer2;
	}

	public byte[] getALine(){
		if (buffer.length < separator.length) return null;
		byte[] result = null;
		int i = containsPacket();
		if (i != -1){
			result = getNBytes(i,this.separator);
		}
		return result;
	}
	
	public int containsPacket(){
		for (int i=0; i<buffer.length-separator.length+1; i++){
			boolean match = true;
			for (int j=0; j<separator.length; j++){
				if (buffer[i+j] != separator[j]) {
					match = false;
					break;
				}
			}
			if(match){
				return i;
			}
		}
		return -1;
	}

	public byte[] getNBytes(int i, byte[] sep) {
		byte[] result;
		result = new byte[i];
		System.arraycopy(buffer, 0, result, 0, i);
		System.out.println("Result:"+new String(result));//@%#$%$#%$#%$#%#$%$#
		byte[] buffer2 = new byte[buffer.length-i-sep.length];
		System.arraycopy(buffer, i+sep.length, buffer2, 0, buffer2.length);
		buffer = buffer2;
		return result;
	}


	public void setSeparator(byte[] separator) {
		this.separator = separator;
	}

	public byte[] getBuffer() {
		return buffer;
	}
	
	
	
}
